package com.bestom.sharingbookcase;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bestom.sharingbookcase.entity.SendHexStep;
import com.bestom.sharingbookcase.entity.TopicStep;
import com.bestom.sharingbookcase.services.MQTTService;
import com.bestom.sharingbookcase.services.MyServiceConnection;
import com.bestom.sharingbookcase.services.SerialManager;
import com.bestom.sharingbookcase.services.WifiService;
import com.bestom.sharingbookcase.services.WifiTools;
import com.bestom.sharingbookcase.util.DataTurn;
import com.bestom.sharingbookcase.util.GPSUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android_serialport_api.SerialPortFinder;

import static androidx.core.os.LocaleListCompat.create;

public class MainActivity extends BaseNfcActivity implements IGetMessageCallBack {

    private TextView textView;
    private Button button;
    private MyServiceConnection serviceConnection;
    private MQTTService mqttService;
    private DataTurn mDataTurn;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("MainActivity", "onCreate !!!!!");

        mDataTurn = new DataTurn();
        mContext = this;
        SharingBookcaseApp.getApplication().setIGetMessageCallBack(this);
        if (!WifiTools.isNetworkConnected(getApplicationContext())) {
            Log.d("MainActivity","网络未连接！正在配网");
            Intent serviceIntent = new Intent(getApplicationContext(), WifiService.class);
            startService(serviceIntent);
        }else {
            Log.d("MainActivity", "run !!!!!");
            startMQttService();
        }
        mayRequestLocation();
        SerialManager.getInstance().openSerialPort("/dev/ttysWK0",115200);

        textView = (TextView) findViewById(R.id.text);
        button = (Button) findViewById(R.id.button);

        Log.e("getAndroidID","getAndroidID:" + getAndroidID(this));

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                MQTTService.publish(String.format(TopicStep.PublishTopic.getTopicString(), SharingBookcaseApp.clientId),"");
                showLocation();
//                SerialManager.getInstance().writeHexToBoard(SerialManager.getInstance().getWriteHex("", SendHexStep.SelectId.getHexString(), ""));
            }
        });
    }

    private void showLocation() {
        if (GPSUtil.getInstance(mContext).isLocationProviderEnabled()) {
            showLocationWithToast();
        } else {
            requestLocation();
        }
    }

    private void showLocationWithToast() {
        Location location = GPSUtil.getInstance(mContext).getLocation();
        Toast.makeText(
                getApplicationContext(),
        "地理位置：lon:" + location.getLongitude() + ";  lat:" + location.getLatitude(),
                Toast.LENGTH_LONG
        ).show();
    }

    private  final int REQUEST_FINE_LOCATION = 1;

    private void mayRequestLocation() {
        //检查系统版本，6.0开始需要动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //检查是否已授权
            int cllPhonePermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION);
            if (cllPhonePermission != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                    //提示用户需要获取位置权限
                }
                //开始权限申请
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
                return;
            }
        }
    }

    /**
     * 权限申请结果处理
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_FINE_LOCATION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //用户已授权，开始扫描
                }else{
                    //用户未授权，提示用户
                }
                break;
        }
    }

    /**
     * 检查地理位置开关是否打开，如果未打开，则提示用户打开地理位置开关。
     * 如果已打开，则显示地理位置；如果被拒绝，直接关闭窗口。
     */
    private void requestLocation() {
        String message = "本应用需要获取地理位置，请打开获取位置的开关";
        Toast.makeText(
                getApplicationContext(),
                message,
                Toast.LENGTH_LONG
        ).show();
    }


    private void startMQttService(){
        serviceConnection = new MyServiceConnection();
        serviceConnection.setIGetMessageCallBack(MainActivity.this);
        Intent intent = new Intent(this, MQTTService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void setSuccess(String str1) {
        Log.d("MainActivity",str1);
        startMQttService();
    }

    @Override
    public void setFail(String str1) {

    }

    @Override
    public void setMessage(String message) {
        textView.setText(message);
        mqttService = serviceConnection.getMqttService();
        mqttService.toCreateNotification(message);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.d("MainActivity", "onNewIntent !!!!!");
        //1.get Tag object
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //read
        Log.d("MainActivity", readTag(detectedTag));
        super.onNewIntent(intent);
    }

    /**
     * write NFC TAG
     */
    private void writeNfcTag(Tag tag) {

        if (tag == null) return;
        NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{NdefRecord.createUri(Uri.parse("https://www.baidu.com/"))});
        int size = ndefMessage.toByteArray().length;
        Ndef ndef = Ndef.get(tag);
        try {
            if (ndef != null) {
                ndef.connect();
                if (!ndef.isWritable()) return;
                if (ndef.getMaxSize() < size) return;

                ndef.writeNdefMessage(ndefMessage);
                Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_SHORT).show();
            } else {
                NdefFormatable ndefFormatable = NdefFormatable.get(tag);
                if (ndefFormatable != null) {
                    ndefFormatable.connect();
                    ndefFormatable.format(ndefMessage);
                    Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "format is failed", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (IOException | FormatException e) {
            e.printStackTrace();
        }
    }

    /**
     * read NFC TAG
     */
    public String readTag(Tag tag) {
        MifareClassic mfc = MifareClassic.get(tag);
        for (String tech : tag.getTechList()) {
            System.out.println(tech);
        }
        try {
            String metaInfo = "";
            //Enable I/O operations to the tag from this TagTechnology object.
            mfc.connect();
            //get TAG type
            int type = mfc.getType();
            //get TAG The number of sectors contained
            int sectorCount = mfc.getSectorCount();
            String typeS = "";
            switch (type) {
                case MifareClassic.TYPE_CLASSIC:
                    typeS = "TYPE_CLASSIC";
                    break;
                case MifareClassic.TYPE_PLUS:
                    typeS = "TYPE_PLUS";
                    break;
                case MifareClassic.TYPE_PRO:
                    typeS = "TYPE_PRO";
                    break;
                case MifareClassic.TYPE_UNKNOWN:
                    typeS = "TYPE_UNKNOWN";
                    break;
                default:
                    break;
            }
            metaInfo += "Card Type：" + typeS + "\nSector:：" + sectorCount + "\nBlock: "
                    + mfc.getBlockCount() + "\nStorage Space: " + mfc.getSize() + "B\n";
            return metaInfo;
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } finally {
            if (mfc != null) {
                try {
                    mfc.close();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG)
                            .show();
                }
            }
        }
        return null;
    }


    public static String getAndroidID(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    @Override
    protected void onDestroy() {
        unbindService(serviceConnection);
        super.onDestroy();
    }
}